// 首页JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // 初始化组件
    Components.initComponents('home');
    
    // 渲染服务网格
    renderServiceGrid();
    
    // 渲染热门服务
    renderHotServices();
    
    // 渲染热门需求
    renderHotDemands();
    
    // 初始化轮播图
    initCarousel();
    
    // 初始化按钮反馈
    CommonUtils.initButtonFeedback();
    
    console.log('✅ 首页加载完成');
});

// 渲染服务网格
function renderServiceGrid() {
    const services = [
        { name: '办公场地', icon: 'fa-building', color: 'from-emerald-50 to-emerald-100', iconColor: 'text-primary' },
        { name: '金融贷款', icon: 'fa-yen-sign', color: 'from-blue-50 to-blue-100', iconColor: 'text-secondary' },
        { name: '劳务派遣', icon: 'fa-users', color: 'from-purple-50 to-purple-100', iconColor: 'text-purple-600' },
        { name: '物流代办', icon: 'fa-truck', color: 'from-orange-50 to-orange-100', iconColor: 'text-accent' },
        { name: '集采代购', icon: 'fa-shopping-basket', color: 'from-pink-50 to-pink-100', iconColor: 'text-pink-600' },
        { name: '农产代销', icon: 'fa-leaf', color: 'from-green-50 to-green-100', iconColor: 'text-primary' },
        { name: '农机服务', icon: 'fa-cogs', color: 'from-indigo-50 to-indigo-100', iconColor: 'text-indigo-600' },
        { name: '更多', icon: 'fa-th', color: 'from-gray-50 to-gray-100', iconColor: 'text-gray-500' }
    ];
    
    const grid = document.getElementById('service-grid');
    if (!grid) return;
    
    grid.innerHTML = services.map(service => `
        <button class="group flex flex-col items-center service-item" data-service="${service.name}">
            <div class="w-14 h-14 rounded-2xl bg-gradient-to-br ${service.color} flex items-center justify-center mb-2 group-hover:scale-110 transition-transform shadow-soft">
                <i class="fa ${service.icon} ${service.iconColor} text-xl"></i>
            </div>
            <span class="text-xs text-center text-text-secondary group-hover:text-primary transition-colors">${service.name}</span>
        </button>
    `).join('');
    
    // 添加点击事件
    grid.querySelectorAll('.service-item').forEach(item => {
        item.addEventListener('click', function() {
            const serviceName = this.dataset.service;
            Navigation.saveServiceDetail(serviceName);
            window.location.href = './pages/service-center-detail.html';
        });
    });
}

// 渲染热门服务
function renderHotServices() {
    const services = [
        {
            image: 'https://images.unsplash.com/photo-1625246333195-78d9c38ad449?w=120&h=120&fit=crop',
            title: '专业农机服务 - 耕地播种一站式',
            desc: '提供专业农机服务，包括耕地、播种、收割等全流程服务，设备先进，经验丰富',
            price: '200/亩起',
            tag: '农机服务',
            tagColor: 'bg-primary/10 text-primary',
            user: '张**',
            phone: '138****5678',
            time: '2小时前',
            views: '1.2k'
        },
        {
            image: 'https://images.unsplash.com/photo-1574943320219-553eb213f72d?w=120&h=120&fit=crop',
            title: '现代化办公场地出租',
            desc: '位于城市中心，交通便利，配套完善，适合各类农业企业办公使用',
            price: '3000/月起',
            tag: '办公场地',
            tagColor: 'bg-secondary/10 text-secondary',
            user: '李**',
            phone: '159****8765',
            time: '5小时前',
            views: '856'
        },
        {
            image: 'https://images.unsplash.com/photo-1579621970563-ebec7560ff3e?w=120&h=120&fit=crop',
            title: '农业金融贷款服务',
            desc: '专注农业领域的金融服务，利率优惠，审批快速，助力农业发展',
            price: '最高500万',
            tag: '金融贷款',
            tagColor: 'bg-accent/10 text-accent',
            user: '王**',
            phone: '186****2345',
            time: '1天前',
            views: '2.1k'
        }
    ];
    
    const container = document.getElementById('hot-services');
    if (!container) return;
    
    container.innerHTML = services.map(service => `
        <div class="bg-white rounded-2xl shadow-soft border border-gray-100 hover:shadow-medium transition-all group cursor-pointer" onclick="window.location.href='./pages/service-detail.html'">
            <div class="p-4">
                <div class="flex gap-3 mb-3">
                    <img src="${service.image}" alt="${service.title}" class="w-20 h-20 object-cover rounded-xl flex-shrink-0">
                    <div class="flex-1 min-w-0">
                        <h3 class="text-sm font-bold text-text-primary mb-1 truncate group-hover:text-primary transition-colors">${service.title}</h3>
                        <p class="text-xs text-text-secondary mb-2 line-clamp-2">${service.desc}</p>
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-2">
                                <span class="text-xs px-2 py-0.5 ${service.tagColor} rounded">${service.tag}</span>
                                <span class="text-xs text-text-secondary"><i class="fa fa-eye mr-1"></i>${service.views}</span>
                            </div>
                            <div class="text-sm font-bold text-primary">¥${service.price}</div>
                        </div>
                    </div>
                </div>
                <div class="flex items-center justify-between pt-3">
                    <div class="flex items-center gap-4 text-xs text-text-secondary">
                        <span><i class="fa fa-user-circle mr-1"></i>${service.user}</span>
                        <span><i class="fa fa-phone mr-1"></i>${service.phone}</span>
                        <span><i class="fa fa-clock-o mr-1"></i>${service.time}</span>
                    </div>
                    <button onclick="event.stopPropagation(); handleContactClick('${service.user}', '${service.phone}')" class="px-3 py-1.5 bg-primary text-white text-xs rounded-lg hover:bg-primary-dark transition-colors">
                        联系我
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

// 渲染热门需求
function renderHotDemands() {
    const demands = [
        {
            title: '急需100亩有机蔬菜种植地',
            desc: '寻找适合有机蔬菜种植的土地，要求土壤肥沃，灌溉条件良好，交通便利',
            tag: '种植合作',
            tagColor: 'bg-primary/10 text-primary',
            topBarColor: 'bg-primary',
            location: '浙江杭州',
            budget: '20万',
            user: '陈**',
            phone: '188****1234',
            time: '2小时前',
            views: '328'
        },
        {
            title: '寻找大型收割机服务',
            desc: '需要专业的收割机团队，约200亩水稻收割，要求设备先进，经验丰富',
            tag: '农机租赁',
            tagColor: 'bg-secondary/10 text-secondary',
            topBarColor: 'bg-secondary',
            location: '江苏南京',
            budget: '5万',
            user: '黄**',
            phone: '139****5678',
            time: '5小时前',
            views: '456'
        }
    ];
    
    const demandsContainer = document.getElementById('hot-demands');
    if (!demandsContainer) return;
    
    demandsContainer.innerHTML = demands.map(demand => `
        <div class="bg-white rounded-2xl shadow-soft border border-gray-100 hover:shadow-medium transition-all group cursor-pointer overflow-hidden" onclick="window.location.href='./pages/demand-detail.html'">
            <div class="h-1 ${demand.topBarColor}"></div>
            <div class="p-4">
                <div class="flex items-start justify-between mb-2">
                    <h3 class="text-sm font-bold text-text-primary group-hover:text-primary transition-colors flex-1 pr-2">${demand.title}</h3>
                    <span class="text-xs px-2 py-1 ${demand.tagColor} rounded flex-shrink-0">${demand.tag}</span>
                </div>
                <p class="text-xs text-text-secondary mb-3 line-clamp-2">${demand.desc}</p>
                <div class="flex items-center justify-between mb-3 pb-3">
                    <div class="flex items-center gap-3 text-xs text-text-secondary">
                        <span><i class="fa fa-map-marker mr-1"></i>${demand.location}</span>
                        <span><i class="fa fa-eye mr-1"></i>${demand.views}</span>
                    </div>
                    <div class="text-sm font-bold text-accent">预算${demand.budget}</div>
                </div>
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3 text-xs text-text-secondary flex-wrap">
                        <span><i class="fa fa-user-circle mr-1"></i>${demand.user}</span>
                        <span><i class="fa fa-phone mr-1"></i>${demand.phone}</span>
                        <span><i class="fa fa-clock-o mr-1"></i>${demand.time}</span>
                    </div>
                    <button onclick="event.stopPropagation(); handleContactClick('${demand.user}', '${demand.phone}')" class="px-3 py-1.5 bg-primary text-white text-xs rounded-lg hover:bg-primary-dark transition-colors flex-shrink-0 ml-2">
                        联系我
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

// 轮播图功能
function initCarousel() {
    let currentSlide = 0;
    const carouselItems = document.querySelectorAll('.carousel-item');
    const indicators = document.querySelectorAll('.carousel-indicator');
    const totalSlides = carouselItems.length;
    let isTransitioning = false;
    
    function goToSlide(index) {
        if (isTransitioning) return;
        isTransitioning = true;
        
        carouselItems.forEach(item => {
            item.classList.remove('active');
            item.classList.add('opacity-0');
        });
        indicators.forEach(indicator => {
            indicator.classList.remove('active');
        });
        
        carouselItems[index].classList.add('active');
        carouselItems[index].classList.remove('opacity-0');
        indicators[index].classList.add('active');
        currentSlide = index;
        
        setTimeout(() => {
            isTransitioning = false;
        }, 700);
    }
    
    // 自动轮播
    let autoPlayInterval = setInterval(() => {
        let nextSlide = (currentSlide + 1) % totalSlides;
        goToSlide(nextSlide);
    }, 5000);
    
    // 点击指示器
    indicators.forEach(indicator => {
        indicator.addEventListener('click', function() {
            clearInterval(autoPlayInterval);
            const index = parseInt(this.getAttribute('data-index'));
            goToSlide(index);
            // 重新启动自动轮播
            autoPlayInterval = setInterval(() => {
                let nextSlide = (currentSlide + 1) % totalSlides;
                goToSlide(nextSlide);
            }, 5000);
        });
    });
}

// 跳转到公告详情
function navigateToAnnouncement(id) {
    const announcements = {
        1: {
            id: 1,
            type: 'policy',
            title: '2024年农业补贴政策发布',
            content: '最新农业补贴政策已出台，符合条件的企业可申请相关补贴。\n\n一、补贴范围\n本次补贴政策主要包括以下几个方面：\n1. 种植补贴：对规模化种植的农业企业给予每亩50-200元的补贴\n2. 农机购置补贴：购买农业机械设备可享受30%-50%的补贴\n3. 绿色农业发展补贴：采用环保种植技术的企业可获得额外补贴\n4. 科技创新补贴：农业技术研发和应用可获得专项资金支持\n\n二、申请条件\n1. 在本地区注册的农业企业或合作社\n2. 具有合法的土地使用权或经营权\n3. 符合环保和质量安全标准\n4. 有完整的财务和经营记录\n\n三、申请流程\n1. 登录平台提交申请材料\n2. 相关部门进行资格审核\n3. 通过审核后进行现场核查\n4. 公示无异议后发放补贴\n\n四、注意事项\n1. 申请材料必须真实有效\n2. 补贴资金专款专用\n3. 接受相关部门的监督检查\n4. 如有违规行为，将追回补贴并处罚\n\n如有疑问，请咨询当地农业部门或平台客服。',
            time: '今天 14:30',
            views: '1.2k'
        },
        2: {
            id: 2,
            type: 'activity',
            title: '新用户注册福利活动',
            content: '新用户注册即送服务优惠券，价值200元，可用于平台内所有服务消费。\n\n活动详情：\n\n一、活动时间\n2024年1月1日 - 2024年3月31日\n\n二、参与方式\n1. 新用户完成注册认证\n2. 填写完整个人信息\n3. 绑定手机号码\n4. 系统自动发放优惠券到账户\n\n三、优惠券使用规则\n1. 单笔订单满500元可使用\n2. 不可与其他优惠同时使用\n3. 有效期为领取后30天内\n4. 仅限本人使用，不可转赠\n\n四、注意事项\n1. 每个用户限领一次\n2. 优惠券不可兑换现金\n3. 活动最终解释权归平台所有\n\n赶快邀请您的朋友一起来注册吧！',
            time: '昨天 10:15',
            views: '856'
        }
    };
    
    const announcement = announcements[id];
    if (announcement) {
        localStorage.setItem('currentAnnouncement', JSON.stringify(announcement));
        window.location.href = './pages/announcement-detail.html';
    }
}

